import POINTLOADING from '@/assets/image/pointloading.gif';
import yuanwen from '@/assets/image/yuanwenicon.png';
import {
  articleRecommend,
  feedback_reasons,
  rewriteSentence,
  search_feedback,
} from '@/services/ant-design-pro/conversation';
import { AILogsCon } from '@/services/models/dataDoc';
import { replaceN } from '@/utils/index';
import { DislikeFilled, LikeFilled } from '@ant-design/icons';
import { Button, Dropdown, message } from 'antd';
import { nanoid } from 'nanoid';
import { useEffect, useState } from 'react';
import { connect } from 'umi';
import ArticleSource from './ArticleSource.js'; //文章来源
import MiniModelArticle from './MiniModelArticle'; //小模型文章来源
import RewriteResult from './RewriteResult';
import Typewriter from './Typewriter.js';
import UserRecover from './UserRecover.js';
const AiCommandLogs: React.FC<any> = (props: any) => {
  const { aiLogs, setAILogs, scrollToBottom } = props;
  const [feedbackReasons, setFeedbackReasons] = useState<any[]>([]); //点踩反馈文案列表

  //存储在页面model的数据
  const { userCommands, curOperationType } = props.conversation;
  //公共更新model的方法
  const updateState = (updateObj: any) => {
    props.dispatch({
      type: 'conversation/updateState',
      payload: updateObj,
    });
  };
  //对话框 回显 用户输入的指令
  const userLogs = async () => {
    const aiLogsUser: any = [];
    if (userCommands?.length) {
      const aiLogsRes: AILogsCon[] = userCommands.map((log: AILogsCon) => {
        return {
          key: +new Date() + Math.random(),
          type: 'user',
          user_command: log,
        };
      });
      const aiLogsCopy = aiLogsUser.concat(aiLogsRes);
      setAILogs(aiLogsCopy);
    } else {
      setAILogs(aiLogsUser);
    }
  };

  //获取点踩的反馈列表
  const getFeedbackReasons = async () => {
    let res = await feedback_reasons({});
    if (res.code === 0) {
      setFeedbackReasons(res.data);
    } else {
      message.error(res.msg);
    }
  };
  useEffect(() => {
    getFeedbackReasons(); //获取点踩的反馈列表
  }, []);

  //回显用户输入的指令数据
  useEffect(() => {
    if (userCommands) {
      userLogs();
    }
  }, [userCommands]);
  //调用仿写重写的接口 data的数据来源有2个 1个是直接点击点赞弹窗的仿写重写 另外一个是点击右侧的重写仿写按钮
  const handleFanGai = async (type: number, data: any) => {
    let fantxt = '这句话写得不错，多仿写几句';
    let gaitxt = '这句话写得不好，需要重写';
    let reason = type === 1 ? fantxt : gaitxt;
    //发送仿写重写的用户 默认文案
    let userRecover = {
      key: nanoid(),
      type: 'userFanGai',
      data: {
        reason,
        text: data?.text,
        range: data?.range ? data?.range : data,
      },
    };
    setAILogs((prev: any) => [...prev, userRecover]);

    setTimeout(() => {
      let systemTxtRecover = {
        key: nanoid(),
        type: 'systemTxtRecover',
        spend: 30,
        data: [`好的，以下是${type === 1 ? '仿写' : '重写'}的内容`],
      };
      setAILogs((prev: any) => [...prev, systemTxtRecover]);
      updateState({
        robotLoading: true,
      });
    }, 500);

    let body = {
      query: data?.text,
      write_type: type,
    };
    const res = await rewriteSentence(body);
    if (res.code === 0) {
      setTimeout(() => {
        updateState({
          robotLoading: false,
          curOperationType: { type: 'input', data: null },
        });
        let rewriteResult = {
          key: nanoid(),
          type: 'rewriteResult',
          data: res.data,
        };
        setAILogs((prev: any) => [...prev, rewriteResult]);
      }, 1000);
    } else {
      updateState({
        robotLoading: false,
        curOperationType: { type: 'input', data: null },
      });
      message.open({
        type: 'error',
        content: res.msg,
      });
    }
  };
  //监听左侧文章组件点赞 点踩 评分的操作
  useEffect(() => {
    if (curOperationType.type === 'fanxie') {
      handleFanGai(1, curOperationType.data);
    }
    if (curOperationType.type === 'gaixie') {
      handleFanGai(2, curOperationType.data);
    }
  }, [curOperationType]);
  //机器人自动回复文案
  useEffect(() => {
    // aiLogs类型
    // 用户输入的指令
    // 通用文字回应
    // 点赞点踩
    // 仿写重写
    // 聊天
    // 机器人loading
    if (aiLogs && aiLogs.length > 0) {
      //aiLogs 判断数组的最后一个的类型 做对应的回复
      let lastLog = aiLogs[aiLogs.length - 1] || null;
      //点赞点踩
      if (lastLog.type === 'userZanCai' && !!lastLog?.data?.range) {
        let zanTxt = '小麦已经收到您的赞！这么棒的文案，需要为您多些几句吗？';
        let caiTxt = '小麦已经收到您的踩！是否需要小麦重新生成几句，来替换不满意的文案？';
        const { type } = lastLog.data;
        let reason = type === 1 ? zanTxt : caiTxt;
        let rewriteTip = {
          key: nanoid(),
          type: 'rewriteTip',
          data: {
            type: type,
            reason: reason,
            text: lastLog?.data?.target_content,
            range: lastLog?.data?.range,
          },
        };
        setAILogs((prev: any) => [...prev, rewriteTip]);
      }
    }
  }, [aiLogs]);

  const items = [
    {
      label: (
        <div>
          <span style={{ marginLeft: '5px' }}>
            <img className="yuanwenicon" src={yuanwen} height={15} width={15} />
            定位到原文
          </span>
        </div>
      ),
      key: '1',
    },
  ];
  //定位到原文
  const dropDownClick: (v: any, item: any) => void = (v, item) => {
    v.domEvent.stopPropagation();
    if (item?.data?.range) {
      updateState({
        curOperationType: {
          type: 'showLocation',
          data: item?.data?.range,
        },
      });
    }
  };

  //查看相关推荐
  const lookRecommend = async (data: any) => {
    updateState({
      robotLoading: true,
    });
    let query = data?.data.keyword;

    //将aiLogs里获取type=miniModelArticle 的data组合成一组
    const filteredDataArray = aiLogs
      .filter((item: any) => item.type === 'miniModelArticle')
      .map((item: any) => item.data)
      .flat();
    //匹配出当前相关推荐已显示的id 用于后台去重
    const ids = filteredDataArray
      .filter((item: any) => item.keyword === data.data.keyword)
      .map((item: any) => item.sentence_id);

    let res = await articleRecommend({ query, ids });
    if (res.code === 0) {
      updateState({
        robotLoading: false,
      });
      const articlesWithKeyword = res.data.articles.map((article: any) => ({
        ...article,
        query: query, //相关推荐的query为数组第一个的main_body
        keyword: data?.data.keyword,
      }));
      let miniModelArticle = {
        key: nanoid(),
        type: 'miniModelArticle',
        isTypewriter: true,
        data: articlesWithKeyword,
      };
      setAILogs((prev: any) => [...prev, miniModelArticle]);
      //小于5条表示后面没有数据了
      if (res.data.articles.length <= 4) {
        setTimeout(() => {
          let systemTxtRecover = {
            key: nanoid(),
            type: 'systemTxtRecover',
            spend: 30,
            data: ['非常抱歉，没有更多结果可供显示，请尝试使用其他关键词。'],
          };
          setAILogs((prev: any) => [...prev, systemTxtRecover]);
        }, 500 + 800 * res?.data?.articles.length);
      } else {
        setTimeout(() => {
          let lookRecommend = {
            key: nanoid(),
            type: 'lookRecommend',
            data: data.data,
          };
          setAILogs((prev: any) => [...prev, lookRecommend]);
        }, 500 + 800 * res?.data?.articles.length);
      }
    } else {
      message.error(res.msg);
      updateState({
        robotLoading: false,
      });
    }
  };

  //踩的反馈提交
  const submitFeedbackCai = async (item: any, item2: any) => {
    let body = {
      query_string: item?.data?.query_string,
      query_result: item?.data?.query_result,
      source: '小模型',
      type: item?.data?.type,
      reason_ids: [item2.id],
    };
    let res = await search_feedback(body);
    if (res.code === 0) {
      let caiTxt = '收到您的反馈，我会总结经验，努力改进的。';
      let zancaiTip = {
        key: nanoid(),
        type: 'userZanCai',
        data: {
          type: item?.data?.type,
          reason: item2.name,
          target_content: item?.data?.sentence,
          range: null,
        },
      };

      setTimeout(() => {
        setAILogs((prev: any) => [...prev, zancaiTip]);
        updateState({
          robotLoading: false,
          curOperationType: {
            type: 'cancelZanCai',
            data: null,
          },
        });
      }, 500);

      setTimeout(() => {
        let systemTxtRecover = {
          key: nanoid(),
          type: 'systemTxtRecover',
          spend: 30,
          data: [caiTxt],
        };
        setAILogs((prev: any) => [...prev, systemTxtRecover]);
      }, 1000);
    } else {
      message.error(res.msg);
    }
  };

  return (
    <>
      {/* <div className=''>

    <RewriteResult data={itemData} setAILogs={setAILogs}  updateState={updateState} scrollToBottom={scrollToBottom}></RewriteResult>
    </div> */}

      {/* <Dropdown   menu={{ items, onClick: (v) => dropDownClick(v, item) }} trigger={['contextMenu']}>
      <div className="commandListBox userType">
        <div className="commandList userCommand">
          <div className="commandList-bd">这个内容写得很好，值得表扬</div>
        </div>
        <div className="commandZanCaiBox">
          <span className="commandZanCai-hd">
            <LikeFilled style={{ color: '#60D9A4' }} />
          </span>
          <div className="commandZanCai-bd">
            <span>活动宣传单位</span>
          </div>
        </div>
      </div>
    </Dropdown> */}
      {/* <MiniModelArticle
       
        data={dt}
        scrollToBottom={scrollToBottom}
     ></MiniModelArticle> */}
      {/* <div className='recommendBox'>
        <span className='recommend-hd'>是否查看更多结果</span>
        <span className='recommend-bd'>
            <Button type="primary">好的</Button>
        </span>
     </div> */}
      {/* <div className='feedbackReasonsWrap'>
       <div className='feedbackReasonsBox'>
          <div className='feedbackReasonsTitle'>很抱歉，小麦的的回答没有让您满意，请说明原因：</div>
          <div className='feedbackReasonsListBox'>
            {
              feedbackReasons && feedbackReasons.length>0 && 
              feedbackReasons.map((item:any)=>{
                return (<div key={item.id} className='feedbackReasonsList'>{item.name}</div>)
              })
            }
          </div>
          <div className='feedbackReasonsFoot'>如有其他问题描述及建议请在下方输入框输入</div>
       </div>
     </div> */}
      {aiLogs.length > 0 &&
        aiLogs.map((item: AILogsCon) => {
          if (item.type === 'user') {
            // 用户的命令
            return (
              <div key={item.key} className="commandList userCommand">
                <div
                  className="commandList-bd"
                  dangerouslySetInnerHTML={{ __html: replaceN(item.user_command) }}
                ></div>
              </div>
            );
          } else if (item.type === 'userRecover') {
            //用户的默认文案
            return (
              <div key={item.key} className="commandList userCommand">
                <div
                  className="commandList-bd"
                  dangerouslySetInnerHTML={{ __html: replaceN(item.data) }}
                ></div>
              </div>
            );
          } else if (item.type === 'systemTxtRecover') {
            // 系统的文字回应
            return (
              // <div className="commandList marginRight systemTxtRecover" key={item.key}>
              //   <Typewriter
              //     className="commandList-bd"
              //     text={item.data[0]}
              //     scrollToBottom={scrollToBottom}
              //   />
              // </div>
              <UserRecover
                key={item.key}
                data={item.data}
                scrollToBottom={scrollToBottom}
                spend={item.spend}
                isTypewriter={item.isTypewriter}
                onComplete={item?.onComplete}
              ></UserRecover>
            );
          } else if (item.type === 'scoreTip') {
            // 评分的回应
            return (
              <div className="commandList" key={item.key}>
                {/* <div className="commandList-bd">{item.data}</div> */}
                <Typewriter className="commandList-bd" text={item.data} />
              </div>
            );
          } else if (item.type === 'userZanCai') {
            //赞和踩的回应
            return (
              <Dropdown
                disabled={!item?.data?.range}
                key={item.key}
                menu={{ items, onClick: (v) => dropDownClick(v, item) }}
                trigger={['contextMenu']}
              >
                {/* {!item?.data?.range} */}
                <div className="commandListBox userType">
                  <div className="commandList userCommand">
                    <div className="commandList-bd">{item?.data?.reason}</div>
                    {/* <Typewriter className="commandList-bd"  text={item?.data?.reason} /> */}
                  </div>
                  <div className="commandZanCaiBox">
                    <span className="commandZanCai-hd">
                      {item.data.type === 1 ? (
                        <LikeFilled style={{ color: '#60D9A4' }} />
                      ) : (
                        <DislikeFilled style={{ color: '#F57070' }} />
                      )}
                    </span>
                    <div className="commandZanCai-bd">
                      <span>{item?.data?.target_content}</span>
                    </div>
                  </div>
                </div>
              </Dropdown>
            );
          } else if (item.type === 'userFanGai') {
            //用户的仿写重写文案
            return (
              <Dropdown
                key={item.key}
                menu={{ items, onClick: (v) => dropDownClick(v, item) }}
                trigger={['contextMenu']}
              >
                <div key={item.key} className="commandListBox userType">
                  <div className="commandList userCommand">
                    <div className="commandList-bd">{item?.data?.reason}</div>
                  </div>
                  <div className="commandZanCaiBox">
                    <div className="commandZanCai-bd">
                      <span>{item?.data?.text}</span>
                    </div>
                  </div>
                </div>
              </Dropdown>
            );
          } else if (item.type === 'rewriteTip') {
            //提示重写仿写
            return (
              <div className="commandListBox" key={item.key}>
                <div className="commandList">
                  <div className="commandList-bd">
                    {item?.data?.reason}
                    {/* <Typewriter className="commandList-bd" text={item?.data?.reason} /> */}
                    <div className="fangxieBtnBox">
                      {item?.data.type === 1 ? (
                        <Button type="primary" onClick={() => handleFanGai(1, item.data)}>
                          仿写
                        </Button>
                      ) : (
                        <Button type="primary" onClick={() => handleFanGai(2, item.data)}>
                          重写
                        </Button>
                      )}
                    </div>
                  </div>
                </div>
              </div>
            );
          } else if (item.type === 'lookSource') {
            //聊天 查看来源
            return (
              <ArticleSource
                key={item.key}
                data={item.data}
                scrollToBottom={scrollToBottom}
              ></ArticleSource>
            );
          } else if (item.type === 'miniModelArticle') {
            // 小模型训练文章
            return (
              <MiniModelArticle
                key={item.key}
                setAILogs={setAILogs}
                updateState={updateState}
                data={item.data}
                scrollToBottom={scrollToBottom}
              ></MiniModelArticle>
            );
          } else if (item.type === 'feedbackReasons') {
            // 是否查看更多结果
            return (
              <div className="feedbackReasonsWrap" key={item.key}>
                <div className="feedbackReasonsBox">
                  <div className="feedbackReasonsTitle">
                    很抱歉，小麦的的回答没有让您满意，请说明原因：
                  </div>
                  <div className="feedbackReasonsListBox">
                    {feedbackReasons &&
                      feedbackReasons.length > 0 &&
                      feedbackReasons.map((item2: any) => {
                        return (
                          <div
                            key={item2.id}
                            className="feedbackReasonsList"
                            onClick={() => submitFeedbackCai(item, item2)}
                          >
                            {item2.name}
                          </div>
                        );
                      })}
                  </div>
                  <div className="feedbackReasonsFoot">
                    如有其他问题描述及建议请在下方输入框输入
                  </div>
                </div>
              </div>
            );
          } else if (item.type === 'lookRecommend') {
            // 是否查看更多结果
            return (
              <div className="recommendBox" key={item.key}>
                <span className="recommend-hd">是否查看更多结果</span>
                <span className="recommend-bd">
                  <Button
                    type="primary"
                    onClick={() => {
                      lookRecommend(item);
                    }}
                  >
                    好的
                  </Button>
                </span>
              </div>
            );
          } else if (item.type === 'rewriteResult') {
            //重写仿写后台返回的结果
            return (
              <div key={item.key}>
                <RewriteResult
                  data={item.data}
                  setAILogs={setAILogs}
                  updateState={updateState}
                  scrollToBottom={scrollToBottom}
                ></RewriteResult>
              </div>
            );
          } else if (item.type === 'robotLoading') {
            //机器人loading
            return (
              <div className="commandList" key={item.key}>
                <div className="commandList-bd">
                  <img className="avatar" src={POINTLOADING} height={14} width={21} />
                </div>
              </div>
            );
          } else {
            return '<></>';
          }
        })}
    </>
  );
};
// export default AiCommandLogs;
export default connect(({ conversation }) => ({ conversation }))(AiCommandLogs);
